<?php
class AuthController extends DefaultBaseController
{
		
   	public function indexAction()
    {
    	$this->_helper->layout()->disableLayout();
		$sLogout = trim($this->getRequest()->getParam('logout', 'no'));
		if ($sLogout == 'yes') {
 			Zend_Auth::getInstance()->clearIdentity();
 			if ($this->_isAJAX) {
 				$this->_helper->json(array('error' => '0', 'redirect' => HTTP_HOST.'/auth'), true, false);
 			}
 			else {
 				$sRedirect = trim($this->getRequest()->getParam('redirect', '/auth'));
 				$this->_redirect(HTTP_HOST.$sRedirect);
 			}
			return;
		}
    	$sLogin = trim($this->getRequest()->getParam('dologin', 'no'));
    	if ($sLogin == 'yes') {
	    	$sLogin = trim($this->getRequest()->getParam('login', ''));
	    	$sPassword = trim($this->getRequest()->getParam('password', ''));
	    	try {
	    		$this->_authenficate($sLogin, $sPassword);
	    	}
	    	catch (Exception $e) {
	    		throw new Exception(_('Неверный логин и/или пароль'));
	    	}
    	}
    	if (Zend_Auth::getInstance()->hasIdentity()) {
    		$sRedirect = ManageBaseController::routeUserTypeDestination();
    		if ($this->_isAJAX) {
    			$this->_helper->json(array('error' => '0', 'redirect' => $sRedirect), true, false);
    		}
    		else {
    			$this->_redirect($sRedirect);
    		}
    		return;
    	}
   		if ($this->_isAJAX) {
   			$this->_helper->json(array('error' => '1', 'errorStr' => _('Неверный логин и/или пароль')), true, false);
   		}
   		if ($sLogin == 'yes') $this->view->error = _('Неверный логин и/или пароль');
    }
    
    private function _authenficate($sUsername, $sPassword) {
    	$db = Zend_Db_Table_Abstract::getDefaultAdapter();
		$authAdapter = new Zend_Auth_Adapter_DbTable($db);
		$authAdapter->setTableName('users');
		$authAdapter->setIdentityColumn('username');
		$authAdapter->setCredentialColumn('password');
		$authAdapter->setCredentialTreatment('MD5(?) AND active = 1');
		$authAdapter->setIdentity($sUsername);
		$authAdapter->setCredential($sPassword);
		$auth = Zend_Auth::getInstance();
		$result = $auth->authenticate($authAdapter);
		if ($result->isValid()) {
			$data = $authAdapter->getResultRowObject(null, 'password');
			$auth->getStorage()->write($data);
			return true;
		}
		return false;
    }
    
}


